package com.cellulargames.control;



import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;

import com.cellulargames.listener.ICanvas;
import com.cellulargames.view.VideoPoker;

public class Painter extends Canvas implements Runnable, CommandListener{

	private static Painter painter;
	
	private ICanvas currentDisplay;
	
	public static ICanvas modalDialog;
	
	private static Thread t;
	
	private Painter(){
		setFullScreenMode(true);		
		addCommand( new Command("Atras", Command.BACK, 0) );		
		setCommandListener(this);
	}
	
	public void start(){		
		if( t == null ){
			t = new Thread(this);
			t.setPriority(Thread.MIN_PRIORITY);
			t.start();		
		}
	}

	public void stop(){
		t.interrupt();
		t = null;
	}
	
	public static void setModalDialog(ICanvas modal) {
		modalDialog = modal;
	}
	
	public static void removeModalDialog() {
		modalDialog = null;
	}
	
	public void setCurrentDisplay(ICanvas currentDisplay) {
		this.currentDisplay = currentDisplay;
	}

	public void run() {
		try{
			
			while( true ){

				/*if( currentDisplay instanceof Menu || currentDisplay instanceof Presentation ){
					repaint();					
					Thread.sleep(40);
				}*/
				
				if( currentDisplay instanceof VideoPoker ){
					repaint();					
					Thread.sleep(40);
				}
										
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void paint(Graphics g) {
		
		g.setColor(0x000000);
		g.fillRect(0, 0, getWidth(), getHeight());
		
		if( currentDisplay != null ){
			currentDisplay.paint(g);
		}
		
		if( modalDialog != null ){
			modalDialog.paint(g);
		}
		
	}
	
	public static final Painter getInstance(){
		if( painter == null ){
			painter = new Painter();
		}
		return painter;
	}
	
	protected void keyPressed(int keyCode) {
		
		if( modalDialog != null ){
			modalDialog.keyPressed(keyCode);			
		}
		else if( currentDisplay != null && modalDialog == null ){
			currentDisplay.keyPressed(keyCode);
		}
	}
	
	protected void keyReleased(int keyCode) {
		
		if( currentDisplay != null ){
			currentDisplay.keyReleased(keyCode);
		}
		
		/*if( (modalDialog != null && modalDialog.equals(currentDisplayEvent)) || currentDisplay.equals(currentDisplayEvent) ){
		
			if( modalDialog != null ){
				if( getGameAction(keyCode) != Canvas.FIRE ){
					modalDialog.keyReleased(keyCode);
				}
				else{
					if( modalDialog instanceof CoinDialog ){
						((CoinDialog)modalDialog).close();
					}
					//else if( modalDialog instanceof Dialog ){
						//((Dialog)modalDialog).close();
					//}
				}
			}
			else if( currentDisplay != null && modalDialog == null ){
				currentDisplay.keyReleased(keyCode);
			}
		
		}*/
	}

	public void commandAction(Command comm, Displayable disp) {
		/*if( currentDisplay instanceof Ruleta ){
			Controller.showMenu();
		}*/
	}
	
}
